#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <iostream>
#include "camserver.h"
#include "camthread.h"

using namespace std;

CameraThread::CameraThread()
: ClientServerThread() {

}

void * CameraThread::Entry() {
	IplImage * frame = ((CameraServer*)this->server)->getCurrentFrame();
	CvMat * mat = ((CameraServer*)this->server)->mat;
	int frameSize = frame->width * frame->height / 8 * frame->nChannels * frame->depth;
	//int frameSize = mat->width * frame->height / 8 * frame->nChannels * frame->depth;
	bool isWork = true;
	char * data = new char [frameSize];
	int count = -1;
	//send frame width
	printf("send video size: %s\n", this->clientSocket->getIpAddress());
	sprintf(data, "%d", frame->width);
	count = this->clientSocket->sendData(data, strlen(data));
	if (count == -1) {
		perror("send");
		delete [] data;
		printf("disconnect: %s\n", this->clientSocket->getIpAddress());
		return 0;
	}
	//send frame height
	sprintf(data, "%d", frame->height);
	count = this->clientSocket->sendData(data, strlen(data));
	if (count == -1) {
		perror("send");
		delete [] data;
		printf("disconnect: %s\n", this->clientSocket->getIpAddress());
		return 0;
	}
	//send frames
	printf("start video stream: %s\n", this->clientSocket->getIpAddress());
	while (isWork) {
		count = this->clientSocket->receiveData(data, frameSize);
		if (count != -1 && !strcmp(data, "getnextframe")) {
			//send frame to client
			wxCriticalSectionLocker open(((CameraServer*)this->server)->protectFrameCS);
			frame = ((CameraServer*)this->server)->getCurrentFrame();
			mat = ((CameraServer*)this->server)->mat;
			int sendedBytes = 0;
			int diff = 0;
			while (sendedBytes < frameSize) {
				diff = frameSize - sendedBytes;
				count = this->clientSocket->sendData(frame->imageData + sendedBytes, diff);
				//count = this->clientSocket->sendData(mat->data + sendedBytes, diff);
				if (count == -1) break;
				sendedBytes += count;
			}
			//-------------------
		} else {
			break;
		}
	}
	delete [] data;
	printf("disconnect: %s\n", this->clientSocket->getIpAddress());
	return 0;
}

void CameraThread::OnExit() {

}
